require 'dbi'
require 'mysql'
class ReportController < ApplicationController
  before_filter :authorize, :except =>[:viewcompany,:viewreport,:createcomment]
  
  verify :method => :post,:only =>[:create,:updateincumbent,:remark], :session => :user_id,
  :redirect_to => { :controller=>"view",:action => "view" }
  
  
  def method_missing(name, *args) 
    render :template=>"index/null"
  end
  
  def viewincumbent
    id = params[:id] || -1
    @incumbent = Incumbent.find_by_id(id,:include=>:Comments)
    if @incumbent
      @incumbent.update_attribute(:view_times,@incumbent.view_times+1)
      @company=@incumbent.Company
      @person=Person.find_by_user_id(@incumbent.user_id)
      @eva=@incumbent.Evaluator
    end
    render :layout => "/layouts/view"
  end
  
  def viewuserincumbent
    id = params[:id] || -1
    @incumbent = Incumbent.find_by_id(id,:include=>:Comments)
    if @incumbent
      @incumbent.tcopy(@incumbent.Tcompany)
      @company=@incumbent.Company
      @person=Person.find_by_user_id(@incumbent.user_id)
      @eva=@incumbent.Tevaluator || @incumbent.Evaluator
    end
    render :layout => "/layouts/view", :template=>"/report/viewincumbent"
  end
  
  def viewreport
    id = params[:id] || -1
    @report = Report.find(id)
    if @report
      @report.update_attribute(:view_times,@report.view_times+1)
      @comments=@report.Comments
      if @report.virtual==0
        @ReportOverseas=@report.ReportOverseas
        @ReportEducations=@report.ReportEducations
      else
        @positionreport=Report.find_by_id(@report.virtual)
        @ReportOverseas=@positionreport.ReportOverseas
        @ReportEducations=@positionreport.ReportEducations
      end
    end
    render :layout => "/layouts/view"   
  end
  
  
  def viewuserreport
    id=params[:id] || -1
    user_id = session[:user_id] || -1
    salarylist=[]
    @report=Report.find_by_id_and_user_id(id,user_id)
    if @report
      if @report.state==2
        @report.incumbents.each do |u|
          salarylist<<u.Evaluator.salary
        end
      salarylist=salarylist.sort
      headcount=salarylist.length
      @report.tile25=salarylist[(0.25*headcount).ceil-1]
      @report.tile50=salarylist[(0.5*headcount).ceil-1]
      @report.tile75=salarylist[(0.75*headcount).ceil-1]
      @report.state=3
      @report.save
      end
      if @report.state==3
        @comments=@report.Comments
        if @report.virtual==0
          @ReportOverseas=@report.ReportOverseas
          @ReportEducations=@report.ReportEducations
        else
          @positionreport=Report.find_by_id(@report.virtual)
          @ReportOverseas=@positionreport.ReportOverseas
          @ReportEducations=@positionreport.ReportEducations
        end
      end
    end
    render :layout => "/layouts/view",:template=>"report/viewreport"
  end
  
  def deletereport
    id = params[:id] || -1
    user_id = session[:user_id] || -1
    report = Report.find_by_id_and_user_id(id,user_id)
    report.destroy
    render(:nothing => true)
  end
  
  def listuserincumbent
    id = params[:id] || -1
    @pages, @objects = paginate :Incumbents,:conditions=>["user_id=? and deleted=0", id],:per_page => 10
    render :template =>"/search/list_incumbent"
  end
  
  def listcompanyincumbent
    id = params[:id] || -1
    @pages, @objects = paginate :Incumbents,:conditions=>["company_id=? and deleted=0", id],:per_page => 10
    render :template =>"/search/list_incumbent"
  end
  
  def listreportincumbent
    id = params[:id] || -1
    report = Report.find_by_id(id)
    if report
      report = report.virtual==0 ? report : Report.find_by_id(report.virtual)
      if report.category==1
        #company report
        @pages, @objects = paginate :Incumbents, 
        :conditions=>["company_id=? and com_included=1", report.ReportCompany.id],:per_page => 10
      elsif report.category==2
        #city report
        @pages, @objects = paginate :Incumbents,
        :conditions=>["city_id=? and effective_year=? and cit_included=1", report.city_id,report.effective_year],:per_page => 10
      elsif report.category==3
        #position report
        @pages, @objects = paginate :Incumbents,
        :conditions=>["position_id=? and city_id=? and effective_year=? and pos_included=1", report.position_id, report.city_id,report.effective_year],:per_page => 10
      else
        #customized report
        @pages, @objects = paginate :Incumbents,
        :joins => "as i inner join Incumbents_Reports as r on i.id=r.incumbent_id",
        :conditions=>["r.report_id=? and r.included=1", report.id],:per_page => 10  
      end
    end
    render :template =>"/search/list_incumbent"
  end
  
  def newincumbent
    flash[:notice]=[]
    flash[:notice]<<["<li>提交一个样本，完成您的分析报告</li>"]
    render :partial=> "/report/create_incumbent",:layout => "/layouts/report"
  end
  
  def createincumbent
    user_id = session[:user_id] || -1
    user = User.find(user_id)
    year = user.Person.texperience
    if params[:companyid]==nil || params[:companyid].to_i==0
      flash[:notice]=Company.flash(params[:company])
    else
      flash[:notice]=[]
      company=Company.find(params[:companyid])
      params[:company][:tgrade]=company.grade
    end
    flash[:notice]=Incumbent.flash(params[:incumbent],params[:company][:tgrade],year) if flash[:notice]==[]
    flash[:notice]=Evaluator.flash(params[:evaluator])if flash[:notice]==[]
    
    unless flash[:notice]==[]
      render :partial=> "/report/create_incumbent",:layout => "/layouts/report"
    else
      if company==nil
        company = Company.new(params[:company]) 
        company.User=user
      end
      incumbent = Incumbent.new(params[:incumbent])
      incumbent.teffective_year = params[:incumbent][:teffective_year].to_i
      incumbent.Tcompany=company       
      incumbent.sub_ip = request.env["REMOTE_HOST"]
      evaluator = Evaluator.new(params[:evaluator])      
      incumbent.User=user
      evaluator.Incumbent=incumbent
      evaluator.temp=0
      evaluator.save
      
      incumbent.create_incumbent_report(company)
      
      flash[:notice]=["<li>谢谢您提供样本！</li>"]
      redirect_to :controller=>'view',:action=> 'view'
    end
  end
  
  def modifyincumbent
    user_id = session[:user_id] || -1
    incumbent_id=params[:id]
    @incumbent = Incumbent.find_by_id_and_user_id(incumbent_id,user_id)
    if @incumbent==nil
      render :inline=>%{<table>
	                     <tr>
		                  <td><%=image_tag "/images/nil.gif"%></td>
		                  <td class="biggray" valign="center"><strong>对不起，你没有权限修改该样本</strong></td>
	                     </tr>
                        </table>},:layout=>"layouts/report"
    else
      @incumbent.teffective_year=@incumbent.teffective_year.to_i
      @evaluator=@incumbent.Tevaluator || @incumbent.Evaluator
      @company=@incumbent.Company
      flash[:notice]=[]
      flash[:notice]<<["<li>修改您的样本</li>"]
      render :partial =>"report/modify_incumbent",:layout => "/layouts/report"
    end
  end
  
  def updateincumbent
    user_id = session[:user_id] || -1
    incumbent_id = params[:id] || -1
    user = User.find(user_id)
    incumbent = Incumbent.find_by_id_and_user_id(incumbent_id,user_id)
    if incumbent
    evaluator=incumbent.Tevaluator || incumbent.Evaluator
    updated=true
    params[:incumbent][:ttitle]=incumbent.ttitle unless params[:incumbent][:ttitle].length<20
    unless params[:incumbent][:ttitle]==incumbent.ttitle
      incumbent.ttitle=params[:incumbent][:ttitle]
      updated=false
    end
    unless params[:incumbent][:tposition_id].to_i==incumbent.tposition_id
      incumbent.tposition_id=params[:incumbent][:tposition_id]
      updated=false
    end
    unless params[:incumbent][:teffective_year]==incumbent.teffective_year
      incumbent.teffective_year=params[:incumbent][:teffective_year]
      updated=false
    end
    unless params[:incumbent][:tcity_id].to_i==incumbent.tcity_id
      incumbent.tcity_id=params[:incumbent][:tcity_id]
      updated=false
    end
    unless params[:evaluator][:salary].to_f==evaluator.salary
      updated=false
    end
    unless updated
      incumbent.updated=0
      incumbent.save
      if evaluator.temp==true
        evaluator.salary = params[:evaluator][:salary]
      else
        evaluator = Evaluator.new(params[:evaluator])
        evaluator.incumbent_id=incumbent.id        
        evaluator.temp=1
      end
      if report=Report.find(:first, 
                            :conditions => ["category=3 and effective_year=? and city_id = ? and position_id=?",incumbent.teffective_year,incumbent.tcity_id,incumbent.tposition_id])
        if report.div_salary==0
          evaluator.confidence= report.aver_salary==evaluator.salary ? 10:0
        else
          temp=evaluator.salary
          temp=report.aver_salary-temp
          temp=temp*temp
          evaluator.confidence=10*(temp.to_f/report.div_salary-1).abs
        end
      else
        evaluator.confidence= 10
      end
      evaluator.save
      incumbent.updatereport()
    end
    end
    redirect_to :controller=>'view',:action=> 'view'
  end
  
  def deleteincumbent
    id = params[:id] || -1
    user_id = session[:user_id] || -1
    incumbents = Incumbent.find(:all,:conditions=>["deleted=0 and user_id=?",user_id])
    if incumbents.length>1
      incumbent=incumbents.find{|u| u.id=id}
      incumbent.kill()
      render(:nothing => true)
    else
      return false
    end
  end
  
  def remark
    id = params[:id] || -1
    @eva = Evaluator.find(id)
    if @eva&&@eva.vote(request.env["REMOTE_HOST"],params[:this][:evaluator])
      render :inline=>'<script type="text/javascript">alert("谢谢对样本的评价");</script><embed src="/flash/vote.swf" flashvars= "high='+@eva.high.to_s+'&med='+@eva.med.to_s+'&low='+@eva.low.to_s+'"type="application/x-shockwave-flash" width="300" height="140"/>'
    else
      render :inline=>'<script type="text/javascript">alert("请勿灌票，谢谢合作");</script><embed src="/flash/vote.swf" flashvars= "high='+@eva.high.to_s+'&med='+@eva.med.to_s+'&low='+@eva.low.to_s+'"type="application/x-shockwave-flash" width="300" height="140"/>'
    end
  end
  
  def startreport
    user_id = session[:user_id] || -1
    session[:method]=nil
    unless @report=session[:report]||Report.find_by_id_and_user_id(params[:id],user_id)
      @report=Report.new
      @report.title = User.find(user_id).name+"的定制分析报告"
      @report.effective_year = Time.now.year
      @report.reference_salary=0.0
    end
  end
  
  def cancelreport
    session[:report]=nil
    session[:method]=nil
    redirect_to :controller=>"index",:action=>"index"
  end
  
  def selectincumbent
    flash[:notice]=Report.flash(params[:report]) if session[:report]==nil
    user_id = session[:user_id] || -1
    unless @report=session[:report]
      @report=Report.new
      @report.title = params[:report][:title]
      @report.effective_year = params[:report][:effective_year]
      @report.reference_salary=params[:report][:reference_salary]
    end
    unless flash[:notice]==[] || session[:report]
      render :template=>"report/startreport"
    else
      @report.user_id=user_id
      @report.category=4
      @report.virtual=0
      @report.state=1
      @report.view_times=0
      @report.reply_times=0
      @report.city_id=0
      @report.position_id=0
      @report.created_time=Time.now
      @report.search_field=@report.title + " " + @report.effective_year
      session[:report]=@report
      session[:method]=session[:method]||params[:select][:method]
      if session[:method].to_i==0
        render :template=>"report/selectincumbent_person"
      else
        render :template=>"report/selectincumbent_industry"
      end
    end
  end
  
  def customizereport
    user_id = session[:user_id] || -1
    @incumbentlist=[]
    unless @report=Report.find_by_id_and_user_id(params[:id],user_id)
      @report=session[:report]
    end   
    @incumbents = @report.incumbents
    if @incumbents.empty?
      if params[:type]=="person"
        age=Incumbent.break_int([params[:ageSelected1],params[:ageSelected2],params[:ageSelected3],params[:ageSelected4],params[:ageSelected5],params[:ageSelected6]],
                                [[0,20],[21,25],[26,30],[31,40],[40,50],[50,100]])
        exp=Incumbent.break_int([params[:expSelected1],params[:expSelected2],params[:expSelected3],params[:expSelected4],params[:expSelected5],params[:expSelected6]],
                                [[0,1],[2,3],[4,5],[6,10],[11,20],[20,70]])
        if params[:male]=="1" and params[:female]=="1"
          person_ids=Person.find(:all,:conditions=>["(oversea_id=? or oversea_id=? or oversea_id=? or oversea_id=? or oversea_id=? )
                                                 and (education_id=? or education_id=? or education_id=? or education_id=? or education_id=? or education_id=? )",
          params[:overseaSelected1],params[:overseaSelected2],params[:overseaSelected3],params[:overseaSelected4],params[:overseaSelected5],
          params[:educationSelected1],params[:educationSelected2],params[:educationSelected3],params[:educationSelected4],params[:educationSelected5],params[:educationSelected6]]).map {|u| [u.user_id,u.birthday.year.to_i,u.experience.to_i] }
        elsif params[:male]=="1"
          person_ids=Person.find(:all,:conditions=>["sex=1 and (oversea_id=? or oversea_id=? or oversea_id=? or oversea_id=? or oversea_id=? )
                                                 and (education_id=? or education_id=? or education_id=? or education_id=? or education_id=? or education_id=? )",
          params[:overseaSelected1],params[:overseaSelected2],params[:overseaSelected3],params[:overseaSelected4],params[:overseaSelected5],
          params[:educationSelected1],params[:educationSelected2],params[:educationSelected3],params[:educationSelected4],params[:educationSelected5],params[:educationSelected6]]).map {|u| [u.user_id,u.birthday.year.to_i,u.experience.to_i] }
        else
          person_ids=Person.find(:all,:conditions=>["sex=2 and (oversea_id=? or oversea_id=? or oversea_id=? or oversea_id=? or oversea_id=? )
                                                 and (education_id=? or education_id=? or education_id=? or education_id=? or education_id=? or education_id=? )",
          params[:overseaSelected1],params[:overseaSelected2],params[:overseaSelected3],params[:overseaSelected4],params[:overseaSelected5],
          params[:educationSelected1],params[:educationSelected2],params[:educationSelected3],params[:educationSelected4],params[:educationSelected5],params[:educationSelected6]]).map {|u| [u.user_id,u.birthday.year.to_i,u.experience.to_i] }
        end
        person_ids.each{|u| @incumbents += Incumbent.find_age_and_exp(u,age,exp)} unless person_ids.empty?
      else
        @incumbents += Incumbent.find(:all,:conditions=>["(company_id=? or company_id=? or company_id=? or company_id=? or company_id=? or company_id=? ) 
                                                      and (position_id=? or position_id=? or position_id=? or position_id=? or position_id=? or position_id=? )
                                                      and (city_id=? or city_id=? or city_id=? or city_id=? or city_id=? or city_id=?)",
        params[:companySelected1],params[:companySelected2],params[:companySelected3],params[:companySelected4],params[:companySelected5],params[:companySelected6],
        params[:positionSelected1],params[:positionSelected2],params[:positionSelected3],params[:positionSelected4],params[:positionSelected5],params[:positionSelected6],
        params[:citySelected1],params[:citySelected2],params[:citySelected3],params[:citySelected4],params[:citySelected5],params[:citySelected6]])
      end
      @incumbents.each{|u| @report.select_incumbent(u)}
    end
    @incumbents.each do |u|
      @incumbentlist<<u.id if u.included.to_i==1
    end 
  end
  
  def savereport
    flash[:notice]=[]
    if params[:flash]
      flash[:notice]<<"<li>该分析报告中没有包含样本，选择需要的样本保存后计算。</li>"
    else
      flash[:notice]<<"<li>该分析报告已经成功保存了。</li>"
    end
    user_id = session[:user_id] || -1
    unless report=Report.find_by_id_and_user_id(params[:id],user_id)
      report=session[:report]
      report.save
      Indexer.index_search_field(report.search_field,2,report.id)
      session[:report]=nil
      session[:method]=nil
    end
    inc=report.incumbents
    for i in 0...inc.length
      report.include_incumbent(inc[0],params[inc[0].id.to_s])
    end
    redirect_to :controller=>'report',:action=> 'customizereport',:id=>report.id
  end
  
  def calculatereport
    id=params[:id]
    user_id = session[:user_id] || -1
    if id
      report=Report.find_by_id_and_user_id(id,user_id)
    else
      report=session[:report]
      report.save
      session[:report]=nil
    end
    inc=report.incumbents.detect {|u| u.included.to_i==1}
    unless inc==nil
      q="CALL customize_report("+report.id.to_s+");"
      db=Mysql.new('127.0.0.1','root','msgp02','sbonline_development')
      db.query(q)
      db.close
      redirect_to :controller=>'report',:action=> 'finishreport',:id=>report.id
    else
      redirect_to :controller=>"report",:action=>"savereport",:id=>report.id,:flash=>"1"
    end
  end
  
  def finishreport
    @id=params[:id]
  end
   
end
